#include "OpenGLDevice.h"

OpenGLDevice::OpenGLDevice (void)
{
}

OpenGLDevice::~OpenGLDevice (void)
{
	UnregisterClass(L"Engine", hInstance);
}

BOOL OpenGLDevice::Init (HINSTANCE hInst, LPCWSTR WinTitle, UINT ScrnWidth,
		   UINT ScrnHeight, UINT ClrDepth, BOOL Fullscreen)
{
	BOOL Success = TRUE;

	hInstance = hInst;
	WindowTitle = WinTitle;
	ScreenWidth = ScrnWidth;
	ScreenHeight = ScrnHeight;
	ColorDepth = ClrDepth;
	FullScreen = Fullscreen;

	Success = InitWindow();
	InitOpenGL();
	DisplayWindow();

	return Success;
}

void OpenGLDevice::BeginRendering (void)
{
	Clear();
}

void OpenGLDevice::EndRendering (void)
{
	SwapBuffers(hDC);
}

void OpenGLDevice::Clear (void)
{
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void OpenGLDevice::SetClearColor (int Red, int Green, int Blue, int Alpha)
{
}

void* OpenGLDevice::GetDrawDevice (void)
{
	return hRC;
}

void OpenGLDevice::InitOpenGL (void)
{
	//Create Context
	int PixelFormat;

	if (FullScreen)
	{
		DEVMODE dmScreenSettings;
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth = ScreenWidth;
		dmScreenSettings.dmPelsHeight = ScreenHeight;
		dmScreenSettings.dmBitsPerPel = ColorDepth;
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
	}
	
	PIXELFORMATDESCRIPTOR pfd=
	{
		sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |	PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA, ColorDepth, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE,
		0, 0, 0, 0
	};

	hDC = GetDC(hWnd);
	PixelFormat = ChoosePixelFormat(hDC, &pfd);
	SetPixelFormat(hDC, PixelFormat, &pfd);
	hRC = wglCreateContext(hDC);
	wglMakeCurrent(hDC,hRC);
	ResizeGLScene();

	//Open GL
	glShadeModel (GL_SMOOTH);
	glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth (1.0f);
	glEnable (GL_DEPTH_TEST);
	glDepthFunc (GL_LEQUAL);
	glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

void OpenGLDevice::ResizeGLScene (void)
{
	glViewport(0, 0, ScreenWidth, ScreenHeight);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(45.0f, (float)ScreenWidth/(float)ScreenHeight, 0.1f, 50.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void OpenGLDevice::CleanOpenGL (void)
{
	if (FullScreen)
		ChangeDisplaySettings(NULL, 0);
	if (hRC)
		wglMakeCurrent(NULL, NULL);
	wglDeleteContext(hRC);
	ReleaseDC(hWnd, hDC);
	DestroyWindow(hWnd);
	UnregisterClass(L"Engine", hInstance);
}